package lvbu.wang.lvbuoperator.services;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qing.library.utils.DateUtils;
import com.qing.library.utils.DesUtils;
import com.qing.library.utils.L;
import com.qing.library.utils.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.JsonMotor;
import lvbu.wang.lvbuoperator.bean.MotorCommandSend;
import lvbu.wang.lvbuoperator.bean.SendCommandResult;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.http.IotHttpHelp;
import lvbu.wang.lvbuoperator.http.IotHttpHelpWS;
import lvbu.wang.lvbuoperator.utils.CommandUtils;
import lvbu.wang.lvbuoperator.utils.StringHelper;

/**
 * Created by DaiQing.Zha on 2016/8/3 0003.
 * Email:1642674371@qq.com
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BluetoothLEService extends Service {

    /*-----------------------常量声明区-----------------------*/
    public static final int Bluetooth_UNCONNECT = 0;                  //蓝牙连接状态---未连接
    public static final int Bluetooth_CONNECTING = 1;                //蓝牙连接状态---连接中
    public static final int Bluetooth_CONNECTED = 2;            //蓝牙连接状态---已连接
    public static final int Bluetooth_SCAN = 3;                 //蓝牙连接状态---扫描中
    private static final long SCAN_PERIOD = 10000;            //扫描时间10s
    private static final int SDK_INT_BLE = 18;               //支持ble的最低sdk版本
    private static final UUID UUID_SERVICE = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");    // 服务
    private static final UUID UUID_WRITE = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");     // 透传，数据通道：向CC254x写数据
    private static final UUID UUID_READ = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");     // 透传，数据通道:接收CC254x发过来的数据(notify方式)
    private static final UUID UUID_WRITE_2 = UUID.fromString("0000ffe2-0000-1000-8000-00805f9b34fb"); // 透传，控制通道:向CC254x写数据
    private static final UUID UUID_WRITE_3 = UUID.fromString("00002abe-0000-1000-8000-00805f9b34fb"); // 透传，控制通道:向CC254x写数据
    public static final int VALUE_BLUETOOTH_COMMAND_OVERTIME = 5000;      // 蓝牙向电机发送命令超时
    public static final int VALUE_BLUETOOTH_COMMAND_KEEP = 60000;      // 蓝牙命令在motorCommandList中的最长保存时间

    /*-----------------------普通成员变量声明区-----------------------*/
    private static boolean mBLESupport = false;                   //用于标记是否支持ble
    public static int mBluetoothStatus = Bluetooth_UNCONNECT;  //蓝牙连接状态
    private static String mBluetoothDeviceAddress;               //上一次 连接成功的蓝牙的连接地址
    private static String mMsgFromBluetooth = "";              //来自蓝牙的信息
    //http://www.cnblogs.com/zdz8207/archive/2012/10/17/bluetooth_ble_android.html
    private static Context mContext;
    private static Handler mHandler;
    private static BluetoothAdapter mBluetoothAdapter;      //代表了移动设备的本地的蓝牙适配器, 通过该蓝牙适配器可以对蓝牙进行基本操作
    private static BluetoothGatt mBluetoothGatt;          //作为中央来使用和处理数据
    private static BluetoothGattCallback mGattCallback; //跟中央（手机）相关的状态和回调
    private static List<MotorCommandSend> motorCommandList = new ArrayList<>(); //APP向电机发送的命令集合
    private static BluetoothAdapter.LeScanCallback mLeScanCallback;  //设备扫描回调函数，if new device found,this method will be called;
    private static List<String> mCodeList = new ArrayList<>();
    public static String BLE_NAME = "";
    static {
        mCodeList.add("A0");
        mCodeList.add("A1");
        mCodeList.add("A2");
        mCodeList.add("A5");
        mCodeList.add("A6");
        mCodeList.add("A7");
        mCodeList.add("A8");
        mCodeList.add("AE");
        mCodeList.add("AF");
        mCodeList.add("B0");
        mCodeList.add("B1");
        mCodeList.add("B5");
        mCodeList.add("B6");
        mCodeList.add("BD");
        mCodeList.add("BE");
        mCodeList.add("BF");
        mCodeList.add("C0");
        mCodeList.add("C1");
        mCodeList.add("C4");
        mCodeList.add("C6");
    }


    @Override
    public void onCreate() {
        super.onCreate();

        mContext = getApplicationContext();
        mHandler = new Handler();

        if (Build.VERSION.SDK_INT >= SDK_INT_BLE) { //首先判断是否支持ble

            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {   // 检查当前手机是否支持ble蓝牙
                mBLESupport = false;
            } else {

                BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
                mBluetoothAdapter = bluetoothManager.getAdapter();
                if (mBluetoothAdapter == null) {    //检查设备上是否支持蓝牙
                    mBLESupport = false;
                } else {

                    mBLESupport = true;
                    if (!mBluetoothAdapter.isEnabled()) {   //蓝牙没有打开则打开
                        mBluetoothAdapter.enable();        //打开蓝牙
                    }
                    mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                        @Override
                        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
//                            String bluetoothAddress = App.getInstance().getMotorInfo().getBluetoothAddress();
                            String bluetoothAddress = BaseActivity.getBluetoothAddress(mContext);
                            if (device.getAddress().equals(bluetoothAddress) && rssi > -100) {

                                L.e("main_BLE", "扫描到了 = " + DateUtils.formatDate(System.currentTimeMillis(), DateUtils.TYPE_01));
                                sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_SCAN_SUCCESS);
                                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                                connectBluetooth(bluetoothAddress);
                            }
                        }
                    };
                }
            }

            /**
             * 跟中央（手机）相关的状态和回调
             */
            mGattCallback = new BluetoothGattCallback() {
                @Override
                public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

                    if (newState == BluetoothProfile.STATE_CONNECTED
                            && status == BluetoothGatt.GATT_SUCCESS) {
                        Log.e("main_BLE", "连接上了 = " + DateUtils.formatDate(System.currentTimeMillis(), DateUtils.TYPE_01));
                        sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_CONNECT_SUCCESS);
                        mBluetoothStatus = Bluetooth_CONNECTED;
                        mBluetoothGatt.discoverServices();  // 必须，否则无法发送和接收数据
                        if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) != Bluetooth_CONNECTED) {
                            BaseActivity.saveMotorDefault_bluetooth_connect_state(mContext, Bluetooth_CONNECTED);    //设置蓝牙状态为已连接
                            sendBroadcastBluetoothConnectStateChanged();
                            Log.e("mainOOOOOOOOOO", "---------------------------------------");
                        }
                    } else {
                        Log.e("main_BLE", "没有连接上 = " + DateUtils.formatDate(System.currentTimeMillis(), DateUtils.TYPE_01));
                        sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_CONNECT_FAIL);
                        mBluetoothStatus = Bluetooth_UNCONNECT;
                        close();
                        mBluetoothGatt = null;
                        BaseActivity.saveMotorDefault_bluetooth_connect_state(mContext, Bluetooth_UNCONNECT);    //设置蓝牙状态为未连接
                        sendBroadcastBluetoothConnectStateChanged();
                    }
                }

                @Override
                public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                    super.onServicesDiscovered(gatt, status);
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        mBluetoothGatt.setCharacteristicNotification(mBluetoothGatt.getService(UUID_SERVICE)
                                .getCharacteristic(UUID_READ), true);// 必须，否则无法接收数据
                        mBluetoothGatt.setCharacteristicNotification(mBluetoothGatt.getService(UUID_SERVICE)
                                .getCharacteristic(UUID_WRITE_3), true);// 必须，否则无法接收数据
                    }
                }

                @Override
                public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                    super.onCharacteristicRead(gatt, characteristic, status);
                }

                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    super.onCharacteristicChanged(gatt, characteristic);
                    Log.e(TAG, "onCharacteristicChanged: " + characteristic.getUuid().toString(),null );
                    if (UUID_READ.toString().equals(characteristic.getUuid().toString())) {
                        Intent intent = new Intent();
                        intent.putExtra("value", characteristic.getValue());
                        intent.setAction(ConstantsValue.ACTION_BLUETOOTH_VALUE);
                        new ContextWrapper(mContext).sendBroadcast(intent);
                        String value = StringUtil.hex2String(characteristic.getValue());
                        Log.e(TAG, "onCharacteristicChanged: 红谷滩" +
                                "" +value,null );
                        doBluetoothMessage(value);
                    }else if (UUID_WRITE_3.toString().equals(characteristic.getUuid().toString())) {
                        BLE_NAME = StringUtil.hex2String(characteristic.getValue());
                        Log.e(TAG, "onCharacteristicChanged: 春风十里不如你" + BLE_NAME, null);
                    }
                    super.onCharacteristicChanged(gatt, characteristic);
                }

                @Override
                public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
                    super.onReadRemoteRssi(gatt, rssi, status);
                    Intent intent = new Intent();
                    intent.putExtra("rssi", rssi);
                    intent.setAction(ConstantsValue.ACTION_BLE_SIGNAL_STRENGTH);
                    new ContextWrapper(mContext).sendBroadcast(intent);
                    L.e("rssi的值是 = " + rssi);
                }
            };
        }
    }

    /*-----------------------普通逻辑方法区-----------------------*/

    /**
     * 蓝牙连接
     *
     * @return
     */
    public static void connect() {
        Log.e("BLETOOTH", "mSelectedAddress = " + BaseActivity.getBluetoothAddress(mContext));
        L.e("main_BLE", "准备连接 = " + DateUtils.formatDate(System.currentTimeMillis(), DateUtils.TYPE_01));
        sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_PREPARE_CONNECT);
        if (!mBLESupport) { // 不支持BLE，不需要连接
            Toast.makeText(mContext, mContext.getString(R.string.toast_comm_bleNotSupport), Toast.LENGTH_SHORT).show();
            return;
        }
        if (!StringHelper.checkBluetoothAddress(BaseActivity.getBluetoothAddress(mContext))) {// 蓝牙地址不正确，不需要连接
            Toast.makeText(mContext, mContext.getString(R.string.toast_comm_bleAddressIsError), Toast.LENGTH_SHORT).show();
            return;
        }
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) != Bluetooth_UNCONNECT) {// 不是未连接状态
            Toast.makeText(mContext, mContext.getString(R.string.toast_comm_bleIsNotUnConnected), Toast.LENGTH_SHORT).show();
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) {   //蓝牙适配器不可用，不需要连接
            sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_BLUETOOTH_ADAPTER_CANNOT_USE);
            if (!mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.enable();       //打开手机蓝牙
            }
            Toast.makeText(mContext, mContext.getString(R.string.xml_comm_bluetoothStatus_adapterCanNotUse), Toast.LENGTH_SHORT).show();
            return;
        }
        BaseActivity.saveMotorDefault_bluetooth_connect_state(mContext, Bluetooth_SCAN);// mBluetoothConnectState = Bluetooth_Connect_State_SCA;// 设置为正在搜索
        sendBroadcastBluetoothConnectStateChanged();  //发送蓝牙状态改变的广播
        mHandler.postDelayed(() -> {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) == Bluetooth_SCAN) { // 如果还是搜索状态，说明没有搜索到，设置为未连接|| || BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) == Bluetooth_CONNECTING
                L.e("main_BLE", "没有扫描到相关设备 = " + DateUtils.formatDate(System.currentTimeMillis(), DateUtils.TYPE_01));
                sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_SCAN_FAIL);
                BaseActivity.saveMotorDefault_bluetooth_connect_state(mContext, Bluetooth_UNCONNECT);// mBluetoothConnectState = Bluetooth_Connect_State_DIS;// 设置为未连接
                sendBroadcastBluetoothConnectStateChanged();  //发送蓝牙状态改变的广播
            }
        }, SCAN_PERIOD);
        mBluetoothAdapter.startLeScan(mLeScanCallback);
        connectBluetooth(BaseActivity.getBluetoothAddress(mContext));
        L.e("main_BLE", "开始扫描 = " + DateUtils.formatDate(System.currentTimeMillis(), DateUtils.TYPE_01));
        sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_START_SCAN);
    }

    /**
     * 蓝牙连接
     *
     * @param address
     * @return
     */
    private static boolean connectBluetooth(String address) {

        BaseActivity.saveMotorDefault_bluetooth_connect_state(mContext, Bluetooth_CONNECTING);   //设置蓝牙连接状态为连接中
        sendBroadcastBluetoothConnectStateChanged();
        if (mBluetoothGatt != null && mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)) {

            sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_CONNECTING_DEVICE);
            return mBluetoothGatt.connect();
        }

        try {
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
            if (device == null) {
                sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_CAN_NOT_GET_RREMOTE_DEVICE);
                return false;
            }
            sendBroadcastBluetoothConnectStep(ConstantsValue.ACTION_BLE_CONNECTING_DEVICE);
            //We want to connect directly,so we set autoConnect; the second param of connectGatt is false indicate auto connect,otherwise not auto connect
            mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
            mBluetoothDeviceAddress = address;
        } catch (Exception e) {
            L.e("main_BLE", "e = " + e.toString());
        }
        return true;
    }

    /**
     * 断开蓝牙连接
     */
    public static void disConnect() {
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            mBluetoothAdapter.cancelDiscovery();
        }
        mBluetoothStatus = Bluetooth_UNCONNECT;
        BaseActivity.saveMotorDefault_bluetooth_connect_state(mContext, Bluetooth_UNCONNECT);
        sendBroadcastBluetoothConnectStateChanged();
        if (mBluetoothGatt != null) {
            mBluetoothGatt.disconnect();
            close();
        }
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) == Bluetooth_CONNECTED) {

            if (mBluetoothGatt != null) {
                mBluetoothGatt.disconnect();
                mBluetoothStatus = Bluetooth_UNCONNECT;
                BaseActivity.saveMotorDefault_bluetooth_connect_state(mContext, Bluetooth_UNCONNECT);
            }
        }
    }

    /**
     * 关闭蓝牙连接
     * after using a given ble device,the app must call this method to ensure resource released properly
     */
    public static void close() {

        if (mBluetoothGatt == null) return;
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * 发送蓝牙状态改变的广播
     * when status of bluetooth have changed,we should send a broadcast to notify other ui
     */
    private static void sendBroadcastBluetoothConnectStateChanged() {
        // 发送广播
        Intent intent = new Intent();
        intent.setAction(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED);
        if (mContext != null) {
            ContextWrapper context = new ContextWrapper(mContext);
            context.sendBroadcast(intent);
        }
        Log.e("mainOOOOOOOOOO", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx = " + BaseActivity.getMotorDefault_bluetooth_connect_state(mContext));
    }

    /**
     * 发送蓝牙连接步骤的广播
     * when status of bluetooth have changed,we should send a broadcast to notify other ui
     */
    private static void sendBroadcastBluetoothConnectStep(String action) {
        // 发送广播
        Intent intent = new Intent();
        intent.setAction(action);
        if (mContext != null) {

            ContextWrapper context = new ContextWrapper(mContext);
            context.sendBroadcast(intent);
        }
    }

    /**
     * 向电机发送命令
     *
     * @param sendCode
     * @param sendContent
     */
    public static SendCommandResult sendCommand(String sendCode, String sendContent) {
        try {
            if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) == Bluetooth_CONNECTED) {
                return sendCommandByBluetooth(sendCode, sendContent);
            } else {
                return sendCommandByHttp(sendCode, sendContent);
            }
        } catch (Exception e) {
            SendCommandResult scr = new SendCommandResult();
            scr.setResult(false);
            scr.setErrorMessage(e.getLocalizedMessage());
            return scr;
        }
    }

    public static String sendCommandByHttp(Long motorId, String sendCode, String sendContent, Context context) { // 通过http发送命令

        if (sendContent.length() < 18) {// sendContent长度不够时，不允许执行
            return "sendContent错误";
        }

        String id = IotHttpHelp.makeMotorCommandAddressId(motorId, sendCode);
        Map<String, Object> queryStrings = new HashMap<String, Object>();
        queryStrings.put("id", id);
        queryStrings.put("motorId", motorId);
        queryStrings.put("sendCode", sendCode);
        queryStrings.put("sendContent", sendContent);
        String source = IotHttpHelpWS.getSource(RouteConstant.SET_MOTOR_COMMAND_AND_ANSWER, queryStrings, true, context);
        // LBLog.i(tag, "source=" + source);
        if (IotHttpHelp.checkSource(source) == true) {
            JsonMotor.MotorCommand motorCommand = new Gson().fromJson(source, JsonMotor.MotorCommand.class);
            if (motorCommand.getAnswerResult().equals("02")) {// 收到应答
                String answerContent = motorCommand.getAnswerContent();
                if (answerContent.subSequence(18, 20).equals("01")) {
                    return "";
                } else {
                    return "电机应答结果：设置失败！";
                }

            } else {// 应答超时或者其他
                return "电机应答结果：" + motorCommand.getAnswerResult() + "";
            }

        } else {

            return IotHttpHelp.source2Message(context, source);
        }

    }

    /**
     * 通过网络向电机发送命令
     *
     * @param sendCode
     * @param sendContent
     * @return
     */
    public static SendCommandResult sendCommandByHttp(String sendCode, String sendContent) {
        Log.e(TAG, "sendCommandByHttp: " + sendCode, null);
        //TODO：通过网络向电机发送信息
        SendCommandResult scr = new SendCommandResult();
        if (sendContent.length() < 18) {// sendContent长度不够时，不允许执行
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.bleServer_commandError));
            Log.e(TAG, "sendCommandByHttp: " + "命令错误", null);
            return scr;
        }
        if (!App.getInstance().getMotorInfo().getIsOnline()) {
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.bleServer_motorIsOffLine));
            Log.e(TAG, "sendCommandByHttp: " + "电机不在线", null);
            return scr;
        }

        String key = sendContent.substring(0, 18);
        if (isMotorCommandExist(key)) {
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.bleServer_commandRepeated));
            return scr;     // 尚有未完成的发送记录，返回
        }
        MotorCommandSend item = new MotorCommandSend();
        item.setKey(key);
        item.setSendDate(new Date());
        motorCommandList.add(item);// 添加一个发送记录
        String id = IotHttpHelp.makeMotorCommandAddressId(App.getInstance().getMotorInfo().getMotorId(), sendCode);
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("motorId", App.getInstance().getMotorInfo().getMotorId());
        params.put("sendCode", sendCode);
        params.put("sendContent", sendContent);
        String data = IotHttpHelp.getData(RouteConstant.SET_MOTOR_COMMAND_AND_ANSWER, params, true, mContext);
        Log.e(TAG, "sendCommandByHttp: " + params, null);
        motorCommandList.remove(item);// 删除一个发送记录
        if (IotHttpHelp.checkSource(data)) {   //正确返回
            JsonMotor.MotorCommand motorCommand = new Gson().fromJson(data, JsonMotor.MotorCommand.class);
            if (motorCommand.getAnswerResult().equals("02")) {  // 收到应答
                scr.setResult(true);
                scr.setAnswerContent(motorCommand.getAnswerContent());
                Log.e(TAG, "sendCommandByHttp: " + "收到应答", null);
                return scr;
            } else {    // 应答超时或者其他
                scr.setResult(false);
                scr.setErrorMessage(mContext.getString(R.string.toast_comm_motorCommandAnswerError));
                return scr;
            }

        } else {    //服务器错误
            scr.setResult(false);
            String errorInfo = IotHttpHelp.source2Message(mContext, data);
            scr.setErrorMessage(errorInfo);
            Log.e(TAG, "sendCommandByHttp: " + "服务器错误" + errorInfo, null);
            return scr;
        }
    }

    /**
     * 通过蓝牙向电机发送命令
     *
     * @param sendCode
     * @param sendContent
     * @return
     */
    @SuppressLint("NewApi")
    public static SendCommandResult sendCommandByBluetooth(final String sendCode, String sendContent) {

        Log.e("mainBluetoothAddress", "bluetooth = " + BaseActivity.getBluetoothAddress(mContext) + " HH = " + BaseActivity.getMotorType(mContext) + " sendCode = " + sendCode + " sendContent = " + sendContent);
        int MOTOR_TYPE = BaseActivity.getMotorType(mContext);
        if (MOTOR_TYPE == ConstantsValue.MOTOR_TYPE_IOT_OPERATION) {
            return sendCommandByBluetoothIot(sendCode, sendContent);
        } else {
            return sendCommandByBluetoothBle(sendCode, sendContent);
        }
    }

    /**
     * 物联网版向电机发送命令
     *
     * @param sendCode
     * @param sendContent
     * @return
     */
    private static SendCommandResult sendCommandByBluetoothIot(final String sendCode, String sendContent) {
        SendCommandResult scr = new SendCommandResult();
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) != Bluetooth_CONNECTED) {
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.bleServer_bleNotConnect));
            L.e("send command by bluetooth", "蓝牙未连接");
            return scr;
        }
        if (sendContent.length() < 18) {    //sendContent长度不够时，不允许执行

            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.bleServer_commandError));
            L.e("send command by bluetooth", "命令错误");
            return scr;
        }
        if (mBluetoothGatt == null || mBluetoothGatt.getService(UUID_SERVICE) == null || mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE) == null) {
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.bleServer_bleNotReady));
            L.e("send command by bluetooth", "蓝牙尚未准备就绪");
            return scr;
        }
        String key = sendContent.substring(0, 18);
        if (isMotorCommandExist(key)) { //判断命令是否重复发送
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.bleServer_commandRepeated));
            return scr;
        }

        MotorCommandSend item = new MotorCommandSend();
        item.setKey(key);
        item.setSendDate(new Date());
        item.setAnswerContent("");
        item.setSendCode(sendCode);

        item.setSendContent(sendContent);
        motorCommandList.add(item);     //添加一个发送记录
        try {
            BluetoothGattCharacteristic gattCharacteristic = mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE);
            byte[] bytes = StringUtil.string2Hex(sendContent);
            gattCharacteristic.setValue(bytes);
            mBluetoothGatt.writeCharacteristic(gattCharacteristic);
            long now = new Date().getTime();
            //while循环的作用，每隔30毫秒，检查一次该命令是否还在motorCommandList中，如果还在motorCommandList中，则表示该命令还没有得到响应
            //如果VALUE_BLUETOOTH_COMMAND_OVERTIME秒后，该命令还在motorCommandList，则表示该命令还没有得到响应，此时我们认为这条命令响应失败
            while (true) {

                for (int i = 0; i < motorCommandList.size(); i++) {
                    MotorCommandSend mcs = motorCommandList.get(i);

                    if (mcs.getKey().equals(key)) {

                        if (!mcs.getAnswerContent().equals("")) { // 收到蓝牙返回
                            scr.setResult(true);
                            scr.setAnswerContent(mcs.getAnswerContent());
                            motorCommandList.remove(item);// 删除发送记录
                            return scr;
                        }
                    }
                }
                long ts = new Date().getTime() - now;
                if (ts > VALUE_BLUETOOTH_COMMAND_OVERTIME) {
                    motorCommandList.remove(item);// 删除发送记录
                    scr.setResult(false);
                    scr.setErrorMessage(mContext.getString(R.string.bleServer_bleNotAnswer));
                    return scr;
                }
                BaseActivity.sleep(30);
            }
        } catch (Exception e) {

            motorCommandList.remove(item);// 删除发送记录
            scr.setResult(false);
            scr.setErrorMessage(e.getLocalizedMessage());
            return scr;
        }
    }

    private static final String TAG = "BluetoothLEService";

    /**
     * 蓝牙版向电机发送命令
     *
     * @param sendCode
     * @param sendContent
     * @return
     */
    public static SendCommandResult sendCommandByBluetoothBle(final String sendCode, String sendContent) {
        Log.e(TAG, "sendCommandByBluetoothBle: " + sendCode + sendContent, null);
        SendCommandResult scr = new SendCommandResult();
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) != Bluetooth_CONNECTED) {    //蓝牙没有连接
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.comm_bleServer_bleNotConnect));
            return scr;
        }
        if (mBluetoothGatt == null || mBluetoothGatt.getService(UUID_SERVICE) == null || mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE) == null) {   //蓝牙尚未准备就绪
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.comm_bleServer_bleNotReady));
            return scr;
        }
        if (isMotorCommandExist(sendCode)) { //判断命令是否重复发送
            scr.setResult(false);
            scr.setErrorMessage(mContext.getString(R.string.comm_bleServer_commandRepeated));
            return scr;
        }

        MotorCommandSend item = new MotorCommandSend();
        item.setKey(sendCode);
        item.setSendDate(new Date());
        item.setAnswerContent("");
        item.setSendCode(sendCode);

        item.setSendContent(sendContent);
        motorCommandList.add(item);     //添加一个发送记录
        try {
            BluetoothGattCharacteristic gattCharacteristic = mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE);
            Log.e("mainNewProtocolHH", "------------------------------------- " + sendContent);
            byte[] bytes = StringUtil.string2Hex(sendContent);
            Log.e("mainNewProtocolHH", "*************************************");
            gattCharacteristic.setValue(bytes);
            mBluetoothGatt.writeCharacteristic(gattCharacteristic);
            long now = new Date().getTime();
            while (true) {

                for (int i = 0; i < motorCommandList.size(); i++) {
                    MotorCommandSend mcs = motorCommandList.get(i);

                    if (mcs.getKey().equals(sendCode)) {

                        if (!mcs.getAnswerContent().equals("")) {// 收到蓝牙返回
                            Log.e(TAG, "sendCommandByBluetoothBle: 收到蓝牙返回",null );
                            scr.setResult(true);
                            scr.setAnswerContent(mcs.getAnswerContent());
                            motorCommandList.remove(item);// 删除发送记录
                            return scr;
                        }
                    }
                }
                long ts = new Date().getTime() - now;
                if (ts > VALUE_BLUETOOTH_COMMAND_OVERTIME) {
                    motorCommandList.remove(item);// 删除发送记录
                    scr.setResult(false);
                    scr.setErrorMessage(mContext.getString(R.string.comm_bleServer_bleNotAnswer));
                    return scr;
                }
                BaseActivity.sleep(30);
            }
        } catch (Exception e) {
            Log.e("mainNewProtocolHH", "error = " + e.toString());
            motorCommandList.remove(item);// 删除发送记录
            scr.setResult(false);
            scr.setErrorMessage(e.getLocalizedMessage());
            return scr;
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static boolean sendSwitchByBluetooth(byte[] bytes) { // 通过蓝牙发送控制电机的命令，包括重启、关闭、开启等

        if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) != Bluetooth_CONNECTED) {
            return false;
        }

        if (mBluetoothGatt == null || mBluetoothGatt.getService(UUID_SERVICE) == null || mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE_2) == null) {
            return false;
        }

        try {
            BluetoothGattCharacteristic gattCharacteristic = mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE_2);
            gattCharacteristic.setValue(bytes);
            mBluetoothGatt.writeCharacteristic(gattCharacteristic);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static boolean sendDataByBluetooth(byte[] bytes) { // 通过蓝牙发送数据

        if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) != Bluetooth_CONNECTED) {
            return false;
        }
        if (mBluetoothGatt == null || mBluetoothGatt.getService(UUID_SERVICE) == null || mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE) == null) {
            return false;
        }

        if (bytes == null) {
            return false;
        }
        if (bytes.length == 0) {
            return false;
        }

        // 向电机发数据
        try {
            BluetoothGattCharacteristic gattCharacteristic = mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE);
            gattCharacteristic.setValue(bytes);
            int ii = 0;
            while (mBluetoothGatt.writeCharacteristic(gattCharacteristic) == false) {
                ii++;
                Thread.sleep(11);
                if (ii > 100000) break;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    /**
     * 判断命令是否重复
     * 首先查找该命令在motorCommandList中是否存在
     * 如果存在，再判断当前时间距离上一次发送该命令的时间是否大于VALUE_BLUETOOTH_COMMAND_KEEP
     * 如果是，则不管该条命令，将其从motorCommandList中删除
     * 如果否，则表示上一条同样的命令尚未处理完
     *
     * @param key
     * @return
     */
    public static boolean isMotorCommandExist(String key) {
        for (int i = 0; i < motorCommandList.size(); i++) {
            MotorCommandSend mcs = motorCommandList.get(i);
            if (mcs != null) {
                if (mcs.getKey().equals(key)) {
                    long ts = new Date().getTime() - mcs.getSendDate().getTime();
                    if (ts > VALUE_BLUETOOTH_COMMAND_KEEP) {
                        motorCommandList.remove(mcs);// 删除发送记录
                        return false;
                    } else {
                        return true;// 尚有未完成的发送记录
                    }
                }
            }
        }
        return false;
    }

    /**
     * 处理从电机返回的蓝牙信息
     *
     * @param value
     */
    private static void doBluetoothMessage(String value) {

        int MOTOR_TYPE = BaseActivity.getMotorType(mContext);
        if (MOTOR_TYPE == ConstantsValue.MOTOR_TYPE_IOT_OPERATION) {
            Log.e("HHHBNBNM", "doBluetoothMessage: 物联网版" + value );
            doBluetoothMessageIot(value);
        } else if (MOTOR_TYPE == ConstantsValue.MOTOR_TYPE_BLE_OPERATION) {
//            doBluetoothMessageBle(value);
            Log.e("HHHBNBNM", "doBluetoothMessage: 蓝牙版" + value);
            doBluetoothMessageBleNewProtocol(value);
        }
    }

    /**
     * 蓝牙版消息处理
     *
     * @param value
     */
    private static void doBluetoothMessageBle(String value) {
        mMsgFromBluetooth += value;
        String headCode = StringHelper.subString(mMsgFromBluetooth, 0, 2);
        int orderCurrentLength = StringHelper.subString(mMsgFromBluetooth, 4, mMsgFromBluetooth.length()).length();
        int orderRealLength = Integer.parseInt(StringHelper.subString(mMsgFromBluetooth, 2, 4), 16);
        if (orderCurrentLength == 0 || orderRealLength == 0 || !"30".equals(headCode)) {
            mMsgFromBluetooth = "";
            return;
        }
        if (orderCurrentLength < orderRealLength * 2) {
            return;
        } else {
            if (orderCurrentLength > orderRealLength * 2) {
                mMsgFromBluetooth = "";
                return;
            }
            for (int i = 0; i < motorCommandList.size(); i++) {
                String decryptData = StringUtil.bytesToHexString(DesUtils.CBCDecrypt(StringUtil.hexStringToBytes(StringHelper.subString(mMsgFromBluetooth, 4, mMsgFromBluetooth.length()))));
                String sendCode = StringHelper.subString(decryptData, 2, 4);
                MotorCommandSend mcs = motorCommandList.get(i);
                Log.e("mainVBN", "------" + "decryptData = " + decryptData + " sendCode = " + sendCode + "key = " + mcs.getKey());
                if (mcs.getKey().equals(sendCode.toUpperCase())) {
                    mcs.setAnswerContent(decryptData);
                    break;
                }
            }
            mMsgFromBluetooth = StringHelper.subString(mMsgFromBluetooth, orderRealLength * 2 + 4);
        }
    }

    /**
     * 新蓝牙协议的消息处理
     *
     * @param value
     */
    private static void doBluetoothMessageBleNewProtocol(String value) {

        mMsgFromBluetooth += value;
        while (true) {
            String headCode = StringHelper.subString(mMsgFromBluetooth, 0, 2);
            int orderCurrentLength = StringHelper.subString(mMsgFromBluetooth, 4, mMsgFromBluetooth.length()).length();
            int orderRealLength = Integer.parseInt(StringHelper.subString(mMsgFromBluetooth, 2, 4), 16);
            Log.e("mainDoBluetooth", "value = " + value
                    + " mMsgFromBluetooth = " + mMsgFromBluetooth
                    + " headCode = " + headCode
                    + " currentLength = " + orderCurrentLength
                    + " realLength = " + (orderRealLength * 2));
            if (orderCurrentLength == 0 || orderRealLength == 0 || !CommandUtils.FIXED_COMMAND_HEAD.equals(headCode)) {
                mMsgFromBluetooth = "";
                break;
            }
            if (orderCurrentLength < orderRealLength * 2) {
                break;
            }
            for (int i = 0; i < motorCommandList.size(); i++) {
                String key = CommandUtils.getCommandKey(mMsgFromBluetooth);
                Log.e("mainDoBluetooth", "key = " + key + " mMsgFromBluetooth = " + mMsgFromBluetooth);
                MotorCommandSend mcs = motorCommandList.get(i);
                if (mcs.getKey().equals(key)) {
                    String str = StringHelper.subString(mMsgFromBluetooth, 0, orderRealLength * 2 + 4);
                    Log.e(TAG, "doBluetoothMessageBleNewProtocol: key" + str,null );
                    mcs.setAnswerContent(StringHelper.subString(mMsgFromBluetooth, 0, orderRealLength * 2 + 4));
                    break;
                }
            }
            mMsgFromBluetooth = StringHelper.subString(mMsgFromBluetooth, orderRealLength * 2 + 4);
            Log.e(TAG, "doBluetoothMessageBleNewProtocol: " + mMsgFromBluetooth,null );
        }
    }

    /**
     * 物联网版消息处理
     *
     * @param value
     */
    private static void doBluetoothMessageIot(String value) {
        String imei = App.getInstance().getMotorInfo().getImei();
        if (mMsgFromBluetooth.contains(imei) && value.contains(imei)) {
            mMsgFromBluetooth = value;
        } else {
            mMsgFromBluetooth = mMsgFromBluetooth + value;  //将上次接收到的蓝牙消息与本次接收到的蓝牙消息进行拼接
            Log.e("mainBLEDOV", "NUM2 value = " + value + " mMsgFromBluetooth = " + mMsgFromBluetooth);
        }
        Log.e("mainBluetoothAddress", "NUM1 value = " + value + " mMsgFromBluetooth = " + mMsgFromBluetooth);
        String sendCode;
        if (mMsgFromBluetooth.length() >= 2) {
            sendCode = mMsgFromBluetooth.substring(0, 2);
            if (!mCodeList.contains(sendCode.toUpperCase())) {
                Log.e("mainBLEDO", "NUM3 COMMAND ERROR1 = " + mMsgFromBluetooth);
                mMsgFromBluetooth = "";
                return;
            }
        }
        if (mMsgFromBluetooth.length() < 20) return;
        sendCode = mMsgFromBluetooth.substring(0, 2);
        /**
         * 收到的消息不是来自于当前绑定的电机
         * 即消息的imei值与当前用户电机的imei值不一致
         * 则将消息清空
         */
        if (!mMsgFromBluetooth.substring(3, 18).equals(App.getInstance().getMotorInfo().getImei())) {
            mMsgFromBluetooth = "";
            Log.e("mainBLEDO", "NUM4 IMEI ERROR");
            return;
        }
        int len = 0;
        if (sendCode.equals("A0")) {// 应答电机锁定
            len = 20;
        }
        if (sendCode.equals("A1")) {// 应答电机解锁
            len = 20;
        }
        if (sendCode.equals("A2")) {// 应答电机解锁
            len = 22;
        }
        if (sendCode.equals("A5")) {// 应答助力等级
            len = 22;
        }
        if (sendCode.equals("A6")) {// 修改超速报警值
            len = 22;
        }
        if (sendCode.equals("A7")) {// 获取车辆当前地理位置
            if (mMsgFromBluetooth.length() < 22) {
                return;
            }
            len = Integer.parseInt(mMsgFromBluetooth.substring(20, 22), 16);//获取当前地理位置的应答指令的第20~22位，他表示一条完整当前地理位置命令的长度
            if ("02".equals(mMsgFromBluetooth.substring(18, 20)) || len == 0) {
                mMsgFromBluetooth = "";
                return;
            }
        }
        if (sendCode.equals("A8")) { //应答重新记录里程数
            if (mMsgFromBluetooth.length() < 26) {
                return;
            }
            String a = mMsgFromBluetooth.substring(20, 21);
            int a_Length = Integer.parseInt(a, 16);

            String b = mMsgFromBluetooth.substring(21, 22);
            int b_Length = Integer.parseInt(b, 16);

            String c = mMsgFromBluetooth.substring(22, 23);
            int c_Length = Integer.parseInt(c, 16);

            String d = mMsgFromBluetooth.substring(23, 24);
            int d_Length = Integer.parseInt(d, 16);

            String e = mMsgFromBluetooth.substring(24, 25);
            int e_Length = Integer.parseInt(e, 16);

            String f = mMsgFromBluetooth.substring(25, 26);
            int f_Length = Integer.parseInt(f, 16);

            int all_length = 26 + a_Length + b_Length + c_Length + d_Length + e_Length + f_Length; // 计算应答总的长度
            len = all_length;
        }
        if (sendCode.equals("AE")) {// 修改车重
            len = 24;
        }
        if (sendCode.equals("AF")) {// 修改载重
            len = 24;
        }
        if (sendCode.equals("B0")) {// 应答电机信息
            len = 42;
        }
        if (sendCode.equals("B1")) {// 应答里程数
            if (mMsgFromBluetooth.length() < 30) {
                return;
            }
            String a = mMsgFromBluetooth.substring(24, 25);
            int a_Length = Integer.parseInt(a, 16);

            String b = mMsgFromBluetooth.substring(25, 26);
            int b_Length = Integer.parseInt(b, 16);

            String c = mMsgFromBluetooth.substring(26, 27);
            int c_Length = Integer.parseInt(c, 16);

            String d = mMsgFromBluetooth.substring(27, 28);
            int d_Length = Integer.parseInt(d, 16);

            String e = mMsgFromBluetooth.substring(28, 29);
            int e_Length = Integer.parseInt(e, 16);

            String f = mMsgFromBluetooth.substring(29, 30);
            int f_Length = Integer.parseInt(f, 16);

            int all_length = 30 + a_Length + b_Length + c_Length + d_Length + e_Length + f_Length; // 计算应答总的长度
            len = all_length;
        }
        if (sendCode.equals("B5")) {// 固件升级
            len = 20;
        }
        if (sendCode.equals("B6")) {// 获取信号强度
            len = 22;
        }
        if (sendCode.equals("BD")) {// 获取陀螺仪角度
            len = 26;
        }
        if (sendCode.equals("BE")) {// 校正陀螺仪
            len = 20;
        }
        if (sendCode.equals("BF")) {// 应答当前速度
            len = 24;
        }

        if (sendCode.equals("C0")) {// 应答当前电压
            len = 24;
        }
        if (sendCode.equals("C1")) {// 应答当前处理器温度
            len = 24;
        }
        if (sendCode.equals("C4")) {//修改助力模式
            len = 22;
        }
        if (sendCode.equals("C6")) { //应答坡度和助力等级
            len = 26;
        }
        if (len == 0) {
            mMsgFromBluetooth = "";
            Log.e("mainBLEDO", "NUM4.1 sendCode = " + sendCode);
            return;
        }
        Log.e("mainBLEDO", "NUM5 len = " + len + " msgLength = " + mMsgFromBluetooth.length());
        if (mMsgFromBluetooth.length() < len) return;
        String answerContent = mMsgFromBluetooth.substring(0, len);
        String key = answerContent.substring(0, 18);
        Log.e("mainBLEDO", "NUM6 answerContent = " + answerContent + " key = " + key + " commSize = " + motorCommandList.size());
        for (int i = 0; i < motorCommandList.size(); i++) {
            MotorCommandSend mcs = motorCommandList.get(i);
            if (mcs != null && mcs.getKey().equals(key)) {
                mcs.setAnswerContent(answerContent);
                Log.e("mainBLEDO", "NUM7 ---成功一条---");
                break;
            } else {
                if (mcs == null) {
                    Log.e("mainBLEDOH", "motorCommandList = mcs is null ####");
                    break;
                }
            }
        }
        Log.e("mainBLEDO", "NUM8 sub之前 = " + mMsgFromBluetooth);
        mMsgFromBluetooth = mMsgFromBluetooth.substring(len);
        Log.e("mainBLEDO", "NUM9 sub之后 = " + mMsgFromBluetooth + " --------------------------------------------------------------------------------------------------- ");
        if (mMsgFromBluetooth.length() >= 2) {   //不是我们的命令，则将其清空掉
            sendCode = mMsgFromBluetooth.substring(0, 2);
            if (!mCodeList.contains(sendCode.toUpperCase())) {
                Log.e("mainBLEDO", "NUM10 COMMAND ERROR2 = " + mMsgFromBluetooth);
                mMsgFromBluetooth = "";
            }
        }
    }

    /**
     * 计算命令正确应答时的长度
     *
     * @param sendCode
     * @return
     */
    private static int calculateCommandLength(String sendCode) {

        int len = 0;
        if (sendCode.equals("A0")) {// 应答电机锁定
            len = 20;
        }
        if (sendCode.equals("A1")) {// 应答电机解锁
            len = 20;
        }
        if (sendCode.equals("A2")) {// 应答电机解锁
            len = 22;
        }
        if (sendCode.equals("A5")) {// 应答助力等级
            len = 22;
        }
        if (sendCode.equals("A6")) {// 修改超速报警值
            len = 22;
        }
        if (sendCode.equals("C4")) {//修改助力模式

            len = 22;
        }
        if (sendCode.equals("A7")) {// 获取车辆当前地理位置
            if (mMsgFromBluetooth.length() < 22) {
                return len;
            }
            len = Integer.parseInt(mMsgFromBluetooth.substring(20, 22), 16);//获取当前地理位置的应答指令的第20~22位，他表示一条完整当前地理位置命令的长度
            if ("02".equals(mMsgFromBluetooth.substring(18, 20)) || len == 0) {
                mMsgFromBluetooth = "";
                return len;
            }
        }
        if (sendCode.equals("A8")) { //应答重新记录里程数

            if (mMsgFromBluetooth.length() < 26) {

                return len;
            }
            String a = mMsgFromBluetooth.substring(20, 21);
            int a_Length = Integer.parseInt(a, 16);

            String b = mMsgFromBluetooth.substring(21, 22);
            int b_Length = Integer.parseInt(b, 16);

            String c = mMsgFromBluetooth.substring(22, 23);
            int c_Length = Integer.parseInt(c, 16);

            String d = mMsgFromBluetooth.substring(23, 24);
            int d_Length = Integer.parseInt(d, 16);

            String e = mMsgFromBluetooth.substring(24, 25);
            int e_Length = Integer.parseInt(e, 16);

            String f = mMsgFromBluetooth.substring(25, 26);
            int f_Length = Integer.parseInt(f, 16);

            len = 26 + a_Length + b_Length + c_Length + d_Length + e_Length + f_Length; // 计算应答总的长度
        }
        if (sendCode.equals("AE")) {// 修改车重
            len = 24;
        }
        if (sendCode.equals("AF")) {// 修改载重
            len = 24;
        }
        if (sendCode.equals("B0")) {// 应答电机信息
            len = 42;
        }
        if (sendCode.equals("B1")) {// 应答里程数
            if (mMsgFromBluetooth.length() < 30) {
                return len;
            }
            String a = mMsgFromBluetooth.substring(24, 25);
            int a_Length = Integer.parseInt(a, 16);

            String b = mMsgFromBluetooth.substring(25, 26);
            int b_Length = Integer.parseInt(b, 16);

            String c = mMsgFromBluetooth.substring(26, 27);
            int c_Length = Integer.parseInt(c, 16);

            String d = mMsgFromBluetooth.substring(27, 28);
            int d_Length = Integer.parseInt(d, 16);

            String e = mMsgFromBluetooth.substring(28, 29);
            int e_Length = Integer.parseInt(e, 16);

            String f = mMsgFromBluetooth.substring(29, 30);
            int f_Length = Integer.parseInt(f, 16);

            len = 30 + a_Length + b_Length + c_Length + d_Length + e_Length + f_Length; // 计算应答总的长度
        }
        if (sendCode.equals("B5")) {// 固件升级
            len = 20;
        }
        if (sendCode.equals("B6")) {// 获取信号强度
            len = 22;
        }
        if (sendCode.equals("BD")) {// 获取陀螺仪角度
            len = 26;
        }
        if (sendCode.equals("BE")) {// 校正陀螺仪
            len = 20;
        }
        if (sendCode.equals("BF")) {// 应答当前速度
            len = 24;
        }

        if (sendCode.equals("C0")) {// 应答当前电压
            len = 24;
        }
        if (sendCode.equals("C1")) {// 应答当前处理器温度
            len = 24;
        }
        if (sendCode.equals("C6")) { //应答坡度和助力等级
            len = 26;
        }
        return len;
    }

    public static BluetoothGatt getmBluetoothGatt() {

        return mBluetoothGatt;
    }

    /**
     * 获取蓝牙连接状态
     */
    public static int getBluetoothState() {

        if (mBluetoothGatt != null) {
            return Bluetooth_CONNECTED;
        } else {
            return Bluetooth_UNCONNECT;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 修改蓝牙名字
     * @param motorName
     * @return
     */
    public static boolean sendChangeMotorName_bluetooth(String motorName) {
        if (BaseActivity.getMotorDefault_bluetooth_connect_state(mContext) != Bluetooth_CONNECTED) {
            return false;
        }
        if (mBluetoothGatt == null || mBluetoothGatt.getService(UUID_SERVICE) == null || mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE_3) == null) {
            return false;
        }
        try {
            BluetoothGattCharacteristic gattCharacteristic = mBluetoothGatt.getService(UUID_SERVICE).getCharacteristic(UUID_WRITE_3);
            gattCharacteristic.setValue(motorName);
            mBluetoothGatt.writeCharacteristic(gattCharacteristic);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

}
